package com.onec.service.channel.service.channel.jft.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.onec.service.channel.entity.ChannelKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 请求utils：
 *
 * @author onec
 */
public class JftRequestUtils {


    private static final Logger logger = LoggerFactory.getLogger(JftRequestUtils.class);

    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 获取当前。
     *
     * @param requestParam
     * @return
     */
    public static String getMd5Str(Map<String, Object> requestParam, String md5Key) {
        //String str = SecureUtil.md5().getSignStr(requestParam) + "md5key=" + md5Key;
        String bodyStr = MapUtil.sortJoin(requestParam, "&", "=", true);
        String allBody = bodyStr + "md5key=" + md5Key;
        return SecureUtil.md5(allBody);
    }

    /**
     * 数据加密：
     *
     * @param requestParam
     * @return
     */
    public static String encryptData(Map<String, Object> requestParam, String encryptKey) {
        String encData = JSONObject.toJSONString(requestParam);
        try {
//            byte[] bytes = AESUtil.encryptAES(encData.getBytes(DEFAULT_CHARSET), encryptKey.getBytes(DEFAULT_CHARSET),
//                    true, "UTF-8");
            AES aes = SecureUtil.aes(encryptKey.getBytes(DEFAULT_CHARSET));
            byte[] bytes = aes.encrypt(encData.getBytes(DEFAULT_CHARSET));
            return new String(bytes, DEFAULT_CHARSET);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return "";
    }

    /**
     * 数据加密：
     *
     * @param
     * @return
     */
    public static JftReturnModel decryptData(String decryptData, String decryptKey) {
        try {
            AES aes = SecureUtil.aes(decryptKey.getBytes(DEFAULT_CHARSET));
            byte[] bytes = aes.decrypt(decryptData.getBytes(DEFAULT_CHARSET));

//            byte[] bytes = SecureUtil.des().decryptAES(decryptData.getBytes(DEFAULT_CHARSET), decryptKey.getBytes(DEFAULT_CHARSET),
//                    true, DEFAULT_CHARSET);
            String decryptDataValue = new String(bytes, DEFAULT_CHARSET);
            logger.info("佳付通数据解密结果：{}", JSONObject.toJSONString(decryptDataValue));
            return JSONObject.parseObject(decryptDataValue, JftReturnModel.class);
        } catch (Exception e) {
            e.printStackTrace();
            JftReturnModel jftReturnModel = new JftReturnModel();
            jftReturnModel.setResCode("9612");
            jftReturnModel.setResMsg("数据解密异常");
            return jftReturnModel;
        }
    }


    public static Map<String, Object> commonMap(String orgCode, String encryptData, String sign) {
        Map<String, Object> commonMap = new HashMap<>();
        commonMap.put("orgCode", orgCode);
        commonMap.put("encryptData", encryptData);
        commonMap.put("signData", sign);
        return commonMap;
    }

    /**
     * 请求上游同时返回结果：
     *
     * @param commonMap
     * @param url
     * @param decryptKey
     * @return
     */
    public static JftReturnModel requestJft(Map<String, Object> commonMap, String url, String decryptKey) {
        String respParam = HttpUtil.post(url, commonMap);//.doPost(url, commonMap, DEFAULT_CHARSET);
        logger.info("佳付通请求URI:{},返回报文：{}，", url, JSONObject.toJSONString(respParam));
        JSONObject jsonObject = JSONObject.parseObject(respParam);
        if (null == jsonObject || jsonObject.containsKey("resCode") && "9016".equals(jsonObject.getString("resCode"))) {
            JftReturnModel jftReturnModel = new JftReturnModel();
            jftReturnModel.setResCode("0000");
            jftReturnModel.setResMsg("上游订单处理异常请查询为准");
            return jftReturnModel;
        }
        if (jsonObject.containsKey("resCode") && !"0000".equals(jsonObject.getString("resCode"))) {
            JftReturnModel jftReturnModel = new JftReturnModel();
            jftReturnModel.setResCode(jsonObject.getString("resCode"));
            jftReturnModel.setResMsg(jsonObject.getString("resMsg"));
            return jftReturnModel;
        }
        return decryptData(jsonObject.getString("encryptData"), decryptKey);
    }

    /**
     * 佳付通，请求和返回；
     *
     * @param channelKey
     * @param requestParam
     * @param orgCode
     * @return
     */
    public static JftReturnModel requestMap(ChannelKey channelKey, Map<String, Object> requestParam, String orgCode, String requestUrl) {
        String sign = JftRequestUtils.getMd5Str(requestParam, channelKey.getSignKey()).toUpperCase();
        String encryptData = JftRequestUtils.encryptData(requestParam, channelKey.getEncryptKey());
        Map<String, Object> param = JftRequestUtils.commonMap(orgCode, encryptData, sign);
        logger.info("佳付通请求URL:{},请求报文：{}", requestUrl, JSONObject.toJSONString(param));
        return requestJft(param, requestUrl, channelKey.getEncryptKey());
    }
}
